package com.example.aigc_education.security.handle;

import com.alibaba.fastjson.JSON;
import com.example.aigc_education.constant.HttpStatus;
import com.example.aigc_education.utils.ResultUtil;
import com.example.aigc_education.utils.WebUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义认证失败处理器
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String msg = String.format("请求访问：%s，认证失败，无法访问系统资源", request.getRequestURI());
        ResultUtil result = new ResultUtil(HttpStatus.UNAUTHORIZED, msg);
        String json = JSON.toJSONString(result);
        WebUtil.renderString(response,json);
    }
}
